<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>EXIF-Orientation 测试</title>
    <style>
        .example-img {
            width: 100px;
            height: auto;
        }
        #exif-table-body {
            border-collapse: collapse;
        }
        #exif-table-body th {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: left;
        }
        #exif-table-body td {
            border: 1px solid #ccc;
            padding: 8px;
        }
    </style>
</head>
<body>
<div style="margin-bottom: 20px">
    <h5>请下载图片进行测试</h5>
    <div>
        <img class="example-img" src="images/orientation-6.JPG" alt="">
    </div>
    <a href="images/orientation-6.JPG" download="orientation-6.JPG">下载测试图片(orientation-6.JPG)</a>
</div>

<div style="margin-bottom: 20px">
    <h5>已生成图片列表</h5>
    <div id="download" style="margin: 0 auto 10px"></div>

</div>

<div style="margin-bottom: 20px">
    <input id="file" type="file" placeholder="请选择图片">
</div>

<div id="preview" style="margin: 0 auto 10px"></div>
<table id="exif-table-body">
    <thead>
        <th>名称</th>
        <th>描述</th>
        <th>值</th>
    </thead>
</table>

<script src="lib/exif-reader.js"></script>
<script src="lib/utils.js"></script>
<script src="lib/modernizr-custom.js"></script>
<script>
  function listTags(tags) {
    console.log('tags', tags);
  }

  function exiforientation() {
    return Modernizr && Modernizr.exiforientation || false;
  }

  function drawImg(file, imgWidth = 0, Orientation, callback) {
    return new Promise(function (resolve, reject) {
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (e) {
        var image = new Image();
        image.src = e.target.result;
        image.onload = function () {
          var canvas = document.createElement('canvas');
          canvas.setAttribute('style', 'max-width: 500px; height: auto');
          var width = this.naturalWidth;
          var height = this.naturalHeight;

          // 获取缩放比例
          var scale = imgWidth ? width / imgWidth : 1;

          if (scale !== 1) {
            width = width / scale;
            height = height / scale;
          }

          canvas.width = width;
          canvas.height = height;
          var ctx = canvas.getContext('2d');
          ctx.drawImage(this, 0, 0, width, height);

          if (!exiforientation() && Orientation != '' && Orientation != 1 && Orientation != undefined) {
            switch (Orientation) {
              case 6://需要顺时针90度旋转
                canvas.width = height;
                canvas.height = width;
                ctx.rotate(90 * Math.PI / 180);
                ctx.drawImage(this, 0, 0, this.naturalWidth, this.naturalHeight, 0, -height, width, height);
                break;
              case 8://需要逆时针90度旋转
                canvas.width = height;
                canvas.height = width;
                ctx.rotate(-90 * Math.PI / 180);
                ctx.drawImage(this, 0, 0, this.naturalWidth, this.naturalHeight, -width, 0, width, height);
                break;
              case 3://需要180度旋转
                ctx.rotate(180 * Math.PI / 180);
                ctx.drawImage(this, 0, 0, this.naturalWidth, this.naturalHeight, -width, -height, width, height);
                break;
            }
          }

          canvas.toBlob(function (blob) {
            resolve(blob);
            callback && callback(blob)
            document.querySelector('#preview').append(canvas);
            // if (canvas.parentNode) {
            //   canvas.parentNode.removeChild(canvas);
            // }
          }, 'image/jpeg', 1);
        };
      };
    });
  }

  // 生成可下载的图片
  function genNoExifImg(fileBlob, name = 'filename.jpg') {
    name = decodeURIComponent(name)
    const a = document.createElement('a')
    a.textContent = `Download(${name})`;
    a.href = URL.createObjectURL(fileBlob);
    a.download = name;
    document.querySelector("#download").appendChild(a)
  }

  function readExifAndDraw(file) {
    console.log('file', file)
    const reader = new FileReader();
    reader.onload = function (readerEvent) {
      try {
        const tags = ExifReader.load(readerEvent.target.result);

        // The MakerNote tag can be really large. Remove it to lower
        // memory usage if you're parsing a lot of files and saving the
        // tags.
        delete tags['MakerNote'];

        exifReaderListTags(tags);
        var Orientation = tags.Orientation && tags.Orientation.value;

        // 可用FormData上传图片
        drawImg(file, undefined, Orientation, (roratedFile) => {
          // 生成可供下载的图片
          genNoExifImg(roratedFile)
        });



        listTags(tags);
      } catch (error) {
        console.log('error', error);
      }
    };
    reader.readAsArrayBuffer(file);
  }

  function handleFileChange(e) {
    const files = e.target.files;
    if(files[0]) {
      readExifAndDraw(files[0])
    }
  }
  const file = document.querySelector('#file');
  file.addEventListener('change', handleFileChange);
</script>
</body>
</html>
